import React, { useEffect, useState } from 'react';
import './near.less';
import AMapLoader from '@amap/amap-jsapi-loader';
import '../../../public/download/font_4238832_nunxwq8b4n/iconfont.css';
import axios from 'axios';
import store from '../../../public/store.png';
import { Modal } from 'antd-mobile';

function near(Props) {
  //按钮的显示隐藏
  let [autoflag, setautoflag] = useState(true);
  let [doorflag, setdoorflag] = useState(true);

  //控制路线的显示
  let [luxian, setluxian] = useState(false);

  // 当前位置
  let [lng, setlng] = useState(null);
  let [lat, setlat] = useState(null);

  //获取自动垃圾的位置
  let [rlng, setRlng] = useState(null);
  let [rlat, setRlat] = useState(null);

  // 商家列表
  let [storelist, setstorelist] = useState([]);

  // 用于请求接口
  useEffect(() => {
    getStoreList();
  }, []);
  const getStoreList = async () => {
    let { data } = await axios.get('http://localhost:3000/ljk/getStoreList');
    console.log(data.data);
    setstorelist(data.data);
  };

  // 用于画地图
  useEffect(() => {
    window._AMapSecurityConfig = {
      securityJsCode: 'c5a4f911d5b2f69ffa9fa59b1cc87e78',
    };
    AMapLoader.load({
      key: 'e1f9aee25e1fbfc02d6a6f14a2639e57',
      version: '2.0',
      plugins: ['AMap.Marker', 'AMap.Driving', 'AMap.Geolocation'],
    }).then((AMap) => {
      // JS API加载完成后获取AMap对象
      const map = new AMap.Map('map', {
        viewMode: '2D', // 默认使用 2D 模式
        zoom: 13, //初始化地图层级
        center: [115.482331, 38.867657], //初始化地图中心点
      });
      //添加浏览器定位
      map.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位，默认：true
          timeout: 10000, // 设置定位超时时间，默认：无穷大
          offset: [10, 20], // 定位按钮的停靠位置的偏移量
          zoomToAccuracy: true, //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          position: 'LB', //  定位按钮的排放位置,  RB表示右下
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition(function (status, result) {
          // console.log(status, 77);
          if (status == 'complete') {
            onComplete(result);
          } else {
            onError(result);
          }
        });
        function onComplete(data) {
          // data是具体的定位信息
          console.log(data);
          setlng(data.position.lng);
          setlat(data.position.lat);
          // 创建一个自定义的div元素

          var customDiv = document.createElement('div');
          customDiv.className = 'point';
          // 创建一个Marker对象
          var marker = new AMap.Marker({
            position: [data.position.lng, data.position.lat], // 设置位置坐标
          });
          // 将自定义的div添加到Marker对象
          marker.setContent(customDiv);
          // 将Marker添加到地图上
          map.add(marker);

          //自动垃圾回收
          // let automatic = [
          //   { lng: data.position.lng + 0.001, lat: data.position.lat + 0.001 },
          //   { lng: data.position.lng - 0.001, lat: data.position.lat - 0.001 },
          // ];
          // console.log(automatic)
          storelist.forEach((item) => {
            // 创建一个自定义的div元素
            var customDiv = document.createElement('div');
            customDiv.className = 'automatic';
            customDiv.innerHTML =
              '<span class="iconfont icon-shangmenhuishouguanli"></span>';
            // 创建一个Marker对象
            var marker = new AMap.Marker({
              position: [item.lng, item.lat], // 设置位置坐标
            });
            // 将自定义的div添加到Marker对象
            marker.setContent(customDiv);

            marker.on('click', () => {
              //添加事件
              function itemData() {
                return (
                  <div className="items-auto" key={item._id}>
                    <div className="items-img">
                      <img src={store} alt="" />
                    </div>
                    <div className="items-info">
                      <div className="items-info-box1">{item.address}</div>
                      <div className="items-info-box2">
                        距离{item.distance}米
                      </div>
                      <div className="items-info-box3">剩余空间 4㎡/64㎡</div>
                    </div>
                  </div>
                );
              }
              if (item && itemData) {
                Modal.alert({
                  title: item.storeName,
                  content: itemData(),
                  showCloseButton: true,
                  confirmText: '手机导航',
                  onConfirm: () => {
                    setRlng(item.lng);
                    setRlat(item.lat);
                    setluxian(true);
                  },
                });
              } else {
                // 处理变量未定义的情况
              }
            });
            // 将Marker添加到地图上
            if (autoflag) {
              map.add(marker);
            }
          });

          // 上门回收
          let doorrabish = [
            {
              lng: data.position.lng + 0.0023,
              lat: data.position.lat + 0.0001,
            },
            {
              lng: data.position.lng - 0.0023,
              lat: data.position.lat - 0.0001,
            },
          ];

          doorrabish.forEach((item) => {
            // 创建一个自定义的div元素
            var customDiv = document.createElement('div');
            customDiv.className = 'doorrabish';
            customDiv.innerHTML = '<span class="iconfont icon-ai49"></span>';
            // 创建一个Marker对象
            var marker = new AMap.Marker({
              position: [item.lng, item.lat], // 设置位置坐标
            });
            // 将自定义的div添加到Marker对象
            marker.setContent(customDiv);
            // 将Marker添加到地图上
            if (doorflag) {
              map.add(marker);
            }
          });
        }

        function onError(data) {
          // 定位出错
          console.log(data, 111);
        }
      });
      //添加路线的
      if (luxian) {
        map.plugin('AMap.Driving', function () {
          var driving = new AMap.Driving({
            map: map,
            // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
            policy: AMap.DrivingPolicy.LEAST_TIME,
          });
          var startLngLat = [lng, lat];
          var endLngLat = [rlng, rlat];

          driving.search(
            new AMap.LngLat(startLngLat[0], startLngLat[1]),
            new AMap.LngLat(endLngLat[0], endLngLat[1]),
            {
              // waypoints: [new AMap.LngLat(114.317433, 30.55351)],
            },
            function (status, result) {
              // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
              if (status === 'complete') {
                console.log('绘制驾车路线完成');
              } else {
                console.log('获取驾车数据失败：' + result);
              }
            },
          );
        });
      }
    });
  });
  //门店收缩
  const show = () => {
    const drawer = document.querySelector('.storeData');
    drawer.classList.toggle('hidden');
  };

  return (
    <div id="Near">
      <div id="map"></div>
      <div className="btns">
        <div
          className={doorflag == true ? 'btn' : 'btn1'}
          onClick={() => {
            setdoorflag(!doorflag);
          }}
        >
          <span className="iconfont icon-qian"></span>
          <div>上门回收</div>
        </div>
        <div
          className={autoflag == true ? 'btn3' : 'btn1'}
          onClick={() => {
            setautoflag(!autoflag);
          }}
        >
          <span className="iconfont icon-kehuhuishouzhan"></span>
          <div>自主投放</div>
        </div>
      </div>
      <div className="storeData">
        <div
          onClick={() => {
            show();
          }}
          className="storeData_btn"
        >
          附近共<span>{storelist.length}</span>家门店
        </div>
        {storelist.map((item, index) => {
          return (
            <div className="items" key={item._id}>
              <div className="items-img">
                <img src={store} alt="" />
              </div>
              <div className="items-info">
                <div className="items-info-box1">{item.storeName}</div>
                <div className="items-info-box2">{item.address}</div>
                <div className="items-info-box3">
                  {item.tags.map((childItem, index) => {
                    return <span key={index}>{childItem}</span>;
                  })}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default near;
